package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.service.goods.SkuSearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SkuSearchServiceImpl implements SkuSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public Map search(Map<String, String> searchMap) throws Exception {
        SearchRequest searchRequest = new SearchRequest("sku");
        searchRequest.types("doc");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();


        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name", searchMap.get("keywords"));
        if(searchMap.get("category")!=null){
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("categoryName", searchMap.get("category"));
            boolQueryBuilder.filter(termQueryBuilder);
        }
        boolQueryBuilder.must(matchQueryBuilder);
        searchSourceBuilder.query(boolQueryBuilder);


        searchRequest.source(searchSourceBuilder);

        //聚合查询（商品分类） 分类集合
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("sku_category").field("categoryName");
        searchSourceBuilder.aggregation(termsAggregationBuilder);

        if (searchMap.get("pageNo")==null){
            searchMap.put("pageNo","1");
        }
        Integer pageNo = Integer.parseInt(searchMap.get("pageNo"));
        Integer size = 10;
        Integer from=(pageNo-1)*size;
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(size);

        //排序
        String sort = searchMap.get("sort");//排序字段
        String sortOrder = searchMap.get("sortOrder");//排序规则
        if(!"".equals(sort)){
            searchSourceBuilder.sort(sort, SortOrder.valueOf(sortOrder));
//            searchSourceBuilder.sort("price", SortOrder.DESC);
        }

        //高亮设置
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.field("name").preTags("<font style='color:red'>").postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);


        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        Map resultMap = new HashMap();
        SearchHits searchHits = searchResponse.getHits();

        SearchHit[] hits = searchHits.getHits();
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        for (SearchHit hit:hits) {
            Map<String, Object> skuMap = hit.getSourceAsMap();
            resultList.add(skuMap);
        }
        resultMap.put("rows",resultList);


        List<Map<String,Object>> resultLists=new ArrayList<Map<String, Object>>();
        for(SearchHit hit:hits){
            Map<String, Object> skuMap = hit.getSourceAsMap();

            //name高亮处理
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField name = highlightFields.get("name");
            Text[] fragments = name.fragments();
            skuMap.put("name",fragments[0].toString());//用高亮的内容替换原内容
            resultLists.add(skuMap);
        }

        Aggregations aggregations = searchResponse.getAggregations();
        Map<String, Aggregation> aggregationMap = aggregations.getAsMap();
        Terms terms = (Terms) aggregationMap.get("sku_category");

        List<? extends Terms.Bucket> buckets =  terms.getBuckets();
        List<String> categoryList=new ArrayList();
        for( Terms.Bucket bucket:buckets ){
            categoryList.add(bucket.getKeyAsString());
        }
        resultMap.put("categoryList",categoryList);

        //分页结果的
        long totalHits = searchHits.getTotalHits();
        long pageCount = (totalHits%size==0 )?totalHits/size:(totalHits/size+1);//
        resultMap.put("totalPages",pageCount);
        return resultMap;
    }
}
